/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 * @author sherin
 */
public class Client extends MIDlet implements CommandListener {
    private Form form;
    public static Display display;
    private List menu = null;
    private List fileBrowserMenu = null;
    Form  loginDetails = null;
    public static String currentMenu;
    FileBrowser file = null;
    GUI gui = null;
    private Connection connectionObject;
    private TextField ip;
    private TextField port;
    private Form messageForm1;
    private Form messageDisplayForm;
    private TextBox messageDisplayBox,fileDisplay;
    private Form userDetails;
    private List services;
    private int rId ;
    private RecordStore rs;
    private List VMList;
    private Form vmFeatures;


    public void startApp() {
        display = Display.getDisplay(this);
        gui = new GUI();
        try {
            openRec();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        menu = gui.getMainMenu();
        mainMenu();

    }
   public void mainMenu() {
       currentMenu = "Main Menu";
       setDisplay( menu );
        
    }
    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        if(unconditional){
            notifyDestroyed();
        }
    }

    public void commandAction(Command c, Displayable d) {
        String label = c.getLabel();        // to capture the commands that are pressed
        System.out.println("Command is "+label);
        if( label.equals("Exit"))
            destroyApp(true);
        else if( label.equals("Back"))
            if( currentMenu.equals("Browser Menu")){
                sendMessageToServer( file.previousFolder());
            }
            else
                mainMenu();
        else if (label.equals("Connect")){
           connectionObject = new Connection(   gui.getIP(), gui.getPort());
           //getServices();
           loginCheck();
        }
        else if(label.equals("View")){

        }
        else if (label.equals("Main"))
            mainMenu();
        else if( label.equals("Send")){
             sendMessageToServer( gui.getMessageFromForm() );
        }
        else if( label.equals("Submit")){            
            authenticateUser();
        }
        else if( label.equals("newMessage")){
            // waiting for a new message from the client to be send to the server
            getMessageToSend();
        }
        else if( label.equals("Delete")){
            sendMessageToServer( file.fileDelete( getSelectedFileOrFolder()));
        }
        else if( label.equals("Copy")){
            file.fileCopy( getSelectedFileOrFolder() );
        }
        else if( label.equals("Paste")){
            sendMessageToServer( file.pasteFile( getSelectedFileOrFolder() ));
        }
        else if( label.equals("Close")){
            sendMessageToServer( file.closeFile());
        }
        else if( label.equals("Save")){
            sendMessageToServer( file.saveFile());
        }
        else if( label.equals("Ok")){

            System.out.println( "This is an ok command ");

            
            System.out.println( "hahahaha");
            if( currentMenu.equals("StartVM")){
                List currentList = ( List)display.getCurrent();
                sendMessageToServer( connectionObject.VBStart( currentList.getString( currentList.getSelectedIndex()) ));
            }
            else if( currentMenu.equals( "createVM")){
                sendMessageToServer( gui.VMCreate( ));

            }
            else if( currentMenu.equals( "EditVM")){
                List currentList = ( List)display.getCurrent();
                String VMName = connectionObject.VBModify(currentList.getString( currentList.getSelectedIndex()) );
                Form editVM = gui.editVMMenu( VMName);
                currentMenu = "EditVMDetails";
                setDisplay( editVM);
            }
            else if( currentMenu.equals( "EditVMDetails")){
                sendMessageToServer(  gui.VMEdit() );
            }
            else if( currentMenu.equals( "RemoveVM")){
                List currentList = ( List)display.getCurrent();
                sendMessageToServer( connectionObject.VBRemove( currentList.getString( currentList.getSelectedIndex()) ));
            }
            else if( currentMenu.equals( "StopVM")){
                List currentList = ( List)display.getCurrent();
                sendMessageToServer( connectionObject.VBStop( currentList.getString( currentList.getSelectedIndex()) ));
            }

        }
        else if( label.equals("Edit")){
            List currentList = ( List)display.getCurrent();
            
        }
        else{                               //to capture the selections from list that is displayed in the window
              List currentList = (List)display.getCurrent();
              if( currentMenu.equals("Main Menu")){
                  switch(currentList.getSelectedIndex()){
                    case 0:     // TODO getting logging in details. change this to a display of those that are available at the present moment
                                //which is being saved in the file by the netx suboption in this same list
                        System.out.println("before getting login details ");                        
                        getServerDetails();
                        break;
                    case 1:  // which is for the settings part
                try {
                    // which is for the settings part
                    System.out.println( "to get settings");
                    getSettings();
                    System.out.println( "after getting settings ");
                    
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                }
                  }
              }
              else if (currentMenu.equals("VMServices")){
                  String action = currentList.getString(currentList.getSelectedIndex());
                  System.out.println( action);
                  System.out.println( "here in services of create ");
                  //sendMessageToServer( "services" );
                  if( action.equals( "Create")){
                      vmFeatures = new Form( "VMCreate");
                      vmFeatures = gui.CreateVM();
                      currentMenu = "createVM";
                      System.out.println( "creating vm ");
                      setDisplay( vmFeatures );
                      
                  }
                  else {
                    sendMessageToServer( connectionObject.VBServiceRequest( action) );
                    
                  }

                  
              }
              else if (currentMenu.equals("Services Menu")){
                  switch(currentList.getSelectedIndex()){
                      case 0:   // TODO if the service is filebrowser. change this case check to variable rather than numbers

                          file = new FileBrowser( );
//TODO find a way around for the value passed when the 'file' is created
                          
                          sendMessageToServer(file.homeDirectory);
                          break;
                      case 1:   //this is simply for a check 
                          getMessageToSend();
                          break;

                  }

              }
              else if (currentMenu.equals("Browser Menu")){
                  String requestFileMessage = file.requestFile( getSelectedFileOrFolder() );
                  sendMessageToServer(requestFileMessage );                  
              }
        }
    }

    private void authenticateUser() {
        String message = connectionObject.authenticateUser( gui.getUsername(), gui.getPassword());
        sendMessageToServer( message );
    }



    private void getSettings() throws RecordStoreException {
        Form settingsForm = gui.getSettingsForm( rs, rId );
        System.out.println( "after menu setting ");
        currentMenu = "Settings Menu";
        setDisplay( settingsForm);
    }


    private void displayMessage(String message) {
        //TODO
        messageDisplayBox = gui.getMessageDisplayBox( message );
        setDisplay( messageDisplayBox );
        System.out.println("after receiving message from the server \n");
    }

    private void getServerDetails() {
        loginDetails = gui.getServerLoginMenu();
        loginDetails.setCommandListener(this);
        display.setCurrent(loginDetails);
    }

    private void getMessageToSend(){
   
        messageForm1 = gui.getMessageForm();       
        setDisplay( messageForm1 );
    
    }
    private void getServices(){
        sendMessageToServer("services");
    }

    private void listServices(String services[]) {
        List servicesMenu = gui.getServicesMenu( services );
        currentMenu = "Services Menu";
        setDisplay( servicesMenu );

    }   

    public void sendMessageToServer(String message){
        try {
            connectionObject.connectServer();
            message = message +"\n";
            connectionObject.writeMessage( message );            
            message = connectionObject.readMessageFromServer();          
            processResponse(message);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void loginCheck() {
        userDetails = gui.getUserDetailsMenu();
        setDisplay( userDetails );
        
    }

    private void openRec() throws RecordStoreException {
        rs = RecordStore.openRecordStore("settings",true);
        String cacheSize = "1024";
        rId = rs.addRecord(cacheSize.getBytes(), 0, cacheSize.length());
        System.out.println( "herererere");
    }

    private void processResponse(String Response){
        System.out.println( "beginning process response");
        String[] ResponseArray = lib.split(Response);
        if( ResponseArray[0].equals("fileBrowser")){
            if( ResponseArray[1].equals("file")){
                fileDisplay = file.displayFile(ResponseArray);
                setDisplay( fileDisplay);
            }
            else if( ResponseArray[1].equals("folder") ) {
                fileBrowserMenu = file.displayFileBrowser( ResponseArray);
                setDisplay( fileBrowserMenu );
            }            
        }
        else if( ResponseArray[0].equals("authentication")){
            if( ResponseArray[1].equals( "true" )){

                services = gui.getServicesMenu1();
                System.out.println( "here after vm menu invocation");
                currentMenu = "VMServices";
                setDisplay( services);
            }
            else if( ResponseArray[1].equals("false")){
                tryAgain();
            }
        }
        else if(ResponseArray[0].equals("services")){
            listServices(ResponseArray);
        }
        else if(ResponseArray[0].equals("VM")){
            System.out.println( "VM service processing ");
            if( ResponseArray[1].equals("StartVM")){
                VMList = gui.listVMs( ResponseArray );
                VMList.setCommandListener(this);
                currentMenu = "StartVM";
                setDisplay( VMList );
            }
            else if( ResponseArray[1].equals("EditVM")){
                VMList = gui.listVMs( ResponseArray );
                VMList.setCommandListener(this);
                currentMenu = "EditVM";
                setDisplay( VMList );
            }
            else if( ResponseArray[1].equals("StopVM")){
                VMList = gui.listVMs( ResponseArray );
                VMList.setCommandListener(this);
                currentMenu = "StopVM";
                setDisplay( VMList );
            }
            else if( ResponseArray[1].equals("RemoveVM")){
                VMList = gui.listVMs( ResponseArray );
                VMList.setCommandListener(this);
                currentMenu = "RemoveVM";
                setDisplay( VMList );
            }
            else if( ResponseArray[1].equals( "success")){
                currentMenu = "VMServices";
                services = gui.getServicesMenu1();
                System.out.println( "successfully executed the action");
                setDisplay( services);
            }
            
        }
        System.out.println( "process request is over ");
    }

   
    private String getSelectedFileOrFolder(){
        return fileBrowserMenu.getString(fileBrowserMenu.getSelectedIndex() );
    }

    private void setDisplay(Form module) {
        module.setCommandListener(this);
        display.setCurrent(module);
    }

    private void setDisplay(List module) {
        module.setCommandListener(this);
        display.setCurrent(module);
    }

    private void setDisplay(TextBox module) {
        module.setCommandListener(this);
        display.setCurrent(module);
    }

    private void tryAgain() {
     Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
     error.setTimeout(Alert.FOREVER);
     userDetails = gui.getUserDetailsMenu();
     userDetails.setCommandListener(this);
     display.setCurrent(error, userDetails);

    }


}
